<?php

namespace app\api\command;

use app\api\controller\Base;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class Expire extends Command
{
    protected function configure()
    {
        $this->setName('expire')->setDescription('expire order handle');
    }

    protected function execute(Input $input, Output $output)
    {
        /* 永不超时 */
        ini_set('max_execution_time', 0);
        $this->doCron();
    }


    public function doCron(){
        header('Content-Type:text/html; charset=utf-8;');

        $cache = cache('command'.__CLASS__);
        if ($cache){
            echo 'running<br />';return false;
        }else{
            cache('command'.__CLASS__,true,1800);
        }
        //过期时间
        $expire = 28800;

        $map['status'] = 1;
        $map['update_time'] = ['< time',time()-$expire];
        Db::name('order')->where($map)->chunk(1000,function ($items){
            foreach ($items as $k => $v){
                Db::startTrans();
                try{
                    $data = Base::refund($v,12);
                    if ($data !== true){
                        var_dump($data);
                    }else{
                        $skill_name = Db::name('skill')->where('skill_id',$v['skill_id'])->cache(300)->value('skill_name');
                        $form_name  = Db::name('skill_form')->where('form_id',$v['form_id'])->cache(300)->value('form_name');
                        $nick_name  = Base::staticInfo('nick_name',$v['user_id']);
                        $date = date('m-d H:i',$v['order_time']);
                        $str  = sprintf('您发起的 %s[%s] %s 对方长时间未确认已自动取消,退款已退回至账户余额',$skill_name,$form_name,$date);
                        $str2 = sprintf('%s发起的 %s[%s] %s  长时间未确认已自动取消,退款已退回对方账户余额',$nick_name,$skill_name,$form_name,$date);
                        Base::sendUsrMsg('system',hashid($v['user_id']),$str);
                        Base::sendUsrMsg('system',hashid($v['to_user']),$str2);
                        Db::commit();
                    }
                }catch (\Exception $e){
                    var_dump($e->getMessage());
                    Db::rollback();
                }
            }
        });

        cache('command'.__CLASS__,null);

    }
}